package com.cqnu.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cqnu.common.Constant;
import com.cqnu.entity.Paper;
import com.cqnu.entity.Student;
import com.cqnu.entity.Teacher;
import com.cqnu.entity.Thesis;
import com.cqnu.entity.ThesisStudent;
import com.cqnu.entity.commonModel.AjaxResult;
import com.cqnu.entity.commonModel.PageParameters;
import com.cqnu.util.DateUtils;
import com.cqnu.util.ListUtil;
import com.cqnu.util.StringUtil;

@Controller
@RequestMapping("/student")
public class StudentController extends BaseController {

	/**
	 * 学生论文查询
	 */
	@RequestMapping("/goQueryThesis.do")
	public String goQueryThesis(HttpServletRequest request, ModelMap modelMap)
			throws Exception {

		Student sessionInfo = (Student) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您还未登录或身份已过期，请登录后进行操作！");
			return "error";
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_STU.equals(sessionRole)) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您没有该资源操作权限！");
			return "error";
		}

		Map<String, Object> map = new HashMap<String, Object>();
		boolean isPass = false;
		ThesisStudent thesisInfo = null;
		// 判断学生是否存在申报课题（状态为'通过'）
		map.put("stuId", sessionInfo.getId());
		List<ThesisStudent> thesisList = thesisStudentService.queryThesisApply(map);
		if (ListUtil.isNotEmpty(thesisList)) {
			for (ThesisStudent ts : thesisList) {
				// 如果课题状态不为'通过',则禁止上传论文
				if (ts.getStatus().equals(Constant.THESIS_STUDENT_PASS)) {
					thesisInfo = ts;
					isPass = true;
				}
			}
		}
		if( isPass ){
			//设置界面数据
			modelMap.put("thesisInfo", JSON.toJSON(thesisInfo));
			
			map.clear();
			
			// 判断学生是否已提交论文（状态为'通过'则隐藏界面 上传 按钮）
			map.put("stuId", sessionInfo.getId());
			boolean disabled = false;
			List<Paper> list = paperService.find(map);
			if (ListUtil.isNotEmpty(list)) {
				for (Paper paper : list) {
					// 如果课题状态不为'不通过',则禁止新增
					if (paper.getState().equals(Constant.PAPER_STUDENT_PASS)
							|| paper.getState().equals(
									Constant.PAPER_STUDENT_SUBMIT)) {
						disabled = true;
					}
				}
			}
			modelMap.addAttribute("disabled", disabled);
			return "/student/queryThesis";
		}
		
		//论文课题noPass
		modelMap.addAttribute("errorMessage", "亲~ 您未申报课题，或者课题未通过！  请先申报课题！");
		return "error";
	}

	/**
	 * 学生论文查询 - 数据列表
	 */
	@RequestMapping("/queryThesisData.do")
	@ResponseBody
	public AjaxResult queryThesisData(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap, PageParameters par)
			throws Exception {

		Student sessionInfo = (Student) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_STU.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();
		Map<String, Object> map = this.getMap(par);
		// 查询当前登录学生的论文信息
		map.put("stuId", sessionInfo.getId());
		
		List<Paper> result = paperService.find(map);
		for( int i=0; i<result.size(); i++ ){
			result.get(i).setNumber(sessionInfo.getNumber());
		}
		
		aj.setRows(result);
		aj.setTotal(paperService.getTotal(this.clearPar(map)).intValue());
		return aj;
	}
	
	
	/**
	 * 学生论文查询 - 删除
	 */
	@RequestMapping("/queryThesisDel.do")
	@ResponseBody
	public AjaxResult queryThesisDel(HttpServletRequest request,
			HttpServletResponse response, int id) throws Exception {

		Student sessionInfo = (Student) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_STU.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();
		Paper paper = paperService.getById(id);
		if (null != paper) {
			// 判断论文的状态，
			if (paper.getState() == Constant.PAPER_STUDENT_NOPASS || paper.getState() == Constant.PAPER_STUDENT_REBACK) {
				if (paperService.delete(id) == 1 ) {
					aj.setSuccess(true);
					aj.setMessage("删除成功！");
					return aj;
				} else {
					aj.setMessage("删除失败！");
				}
			} else {
				aj.setMessage("论文已'通过'或'正在审核'，不允许删除!");
			}
		} else {
			aj.setMessage("操作失败！");
		}
		aj.setSuccess(false);
		return aj;
	}


	/**
	 * 学生课题申报
	 */
	@RequestMapping("/goThesisApply.do")
	public String goThesisApply(HttpServletRequest request, ModelMap modelMap) {

		Student sessionInfo = (Student) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您还未登录或身份已过期，请登录后进行操作！");
			return "error";
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_STU.equals(sessionRole)) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您没有该资源操作权限！");
			return "error";
		}

		Map<String, Object> map = new HashMap<String, Object>();

		// 拉取专业
		map.put("majorId", sessionInfo.getMajorId());
		modelMap.addAttribute("major",
				JSON.toJSON(majorService.find(map).get(0)));

		map.clear();

		// 判断学生是否存在申报课题（状态不为'不通过'）
		map.put("stuId", sessionInfo.getId());
		boolean disabled = false;
		List<ThesisStudent> list = thesisStudentService.find(map);
		if (ListUtil.isNotEmpty(list)) {
			for (ThesisStudent ts : list) {
				// 如果课题状态不为'不通过',则禁止新增
				if (!ts.getStatus().equals(Constant.THESIS_STUDENT_NOPASS)) {
					disabled = true;
				}
			}
		}
		modelMap.addAttribute("disabled", disabled);
		return "student/thesisApply";
	}

	/**
	 * 学生课题申报 - 数据列表
	 */
	@RequestMapping("/thesisApplyData.do")
	@ResponseBody
	public AjaxResult thesisApplyData(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap, PageParameters par)
			throws Exception {

		Student sessionInfo = (Student) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_STU.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();
		Map<String, Object> map = this.getMap(par);
		// 查询当前登录学生的申报信息
		map.put("stuId", sessionInfo.getId());

		aj.setRows(thesisStudentService.queryThesisApply(map));
		aj.setTotal(thesisStudentService.getTotal(this.clearPar(map)).intValue());
		return aj;
	}

	/**
	 * 学生课题申报 - 增加或修改
	 */
	@RequestMapping("/addOrUpdateThesisApply.do")
	@ResponseBody
	public AjaxResult addOrUpdateThesisApply(HttpServletRequest request,
			HttpServletResponse response, ThesisStudent thesisStu)
			throws Exception {

		Student sessionInfo = (Student) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_STU.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();
		if (thesisStu.getId() != null) {
			if (null != thesisStudentService.getById(thesisStu.getId())) {
				if (thesisStudentService.update(thesisStu) == 1) {
					aj.setSuccess(true);
					aj.setMessage("修改成功！");
					return aj;
				}
			}
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			// 判断学生是否存在申报课题（状态不为'不通过'）
			map.put("stuId", sessionInfo.getId());
			List<ThesisStudent> list = thesisStudentService.find(map);
			if (ListUtil.isNotEmpty(list)) {
				for (ThesisStudent ts : list) {
					// 如果课题状态不为'不通过',则禁止新增
					if (!ts.getStatus().equals(Constant.THESIS_STUDENT_NOPASS)) {
						aj.setSuccess(false);
						aj.setMessage("申报失败~你已提交课题!");
						return aj;
					}
				}
			}
			// 第一次提交课题，设置信息
			thesisStu.setStuId(sessionInfo.getId());
			thesisStu.setCreattime(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
			thesisStu.setStatus(Constant.THESIS_STUDENT_SUBMIT);
			int rs = thesisStudentService.add(thesisStu);
			if (rs == 1) {
				aj.setSuccess(true);
				aj.setMessage("添加成功！");
				return aj;
			}
		}
		aj.setSuccess(false);
		aj.setMessage("操作失败！");
		return aj;
	}

	/**
	 * 学生课题申报 - 删除
	 */
	@RequestMapping("/delthesisApply.do")
	@ResponseBody
	public AjaxResult delthesisApply(HttpServletRequest request,
			HttpServletResponse response, int id) throws Exception {

		Student sessionInfo = (Student) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_STU.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();
		ThesisStudent thesisStudent = thesisStudentService.getById(id);
		if (null != thesisStudent) {
			// 判断申报课题审核状态，仅当状态为'不通过'时，可以删除
			if (thesisStudent.getStatus() == Constant.THESIS_STUDENT_NOPASS) {
				if (thesisStudentService.delete(id) == 1) {
					aj.setSuccess(true);
					aj.setMessage("删除成功！");
					return aj;
				} else {
					aj.setMessage("删除失败！");
				}
			} else {
				aj.setMessage("课题已'提交审核'或'审核通过'，不允许删除!");
			}
		} else {
			aj.setMessage("操作失败！");
		}
		aj.setSuccess(false);
		return aj;
	}

	/**
	 * 获取课题下拉框数据,课题信息
	 */
	@RequestMapping("/getThesisInfo.do")
	@ResponseBody
	public List<Thesis> getThesisInfo(HttpServletRequest request,
			ModelMap modelMap, String idStr) {

		if (StringUtil.isBlank(idStr)) {
			return null;
		}
		int majorId = Integer.parseInt(idStr);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("majorId", majorId);
		return thesisService.find(map);
	}

	/**
	 * 获取课题下拉框数据，教师信息
	 */
	@RequestMapping("/getTeacherInfo.do")
	@ResponseBody
	public List<Teacher> getTeacherInfo(HttpServletRequest request,
			ModelMap modelMap, String idStr) {

		if (StringUtil.isBlank(idStr)) {
			return null;
		}
		int majorId = Integer.parseInt(idStr);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("majorId", majorId);
		return teacherService.find(map);
	}

}
